package com.ojoin.trade.common.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ojoin.trade.common.Constants;

public class BankCardUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(BankCardUtils.class);

    /**
     * 银行bin
     */
    private static Map<String,String> bankBinMappings;
	
	static {
        InputStream is = null;
        try {
            String fileName = "/binList.properties";
            is = BankCardUtils.class.getResourceAsStream(fileName);
            byte[] fileCBytes;
            fileCBytes = IOUtils.toByteArray(is);
            BankCardUtils.loadForbiddenWords(fileCBytes);
        } catch (IOException e) {
        	LOGGER.error("binList.properties not find");
        } finally {
            IOUtils.closeQuietly(is);
        }

    }
	
	private static void loadForbiddenWords(byte[] fileCBytes) throws IOException {
        Reader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(fileCBytes), Constants.ENCODING));
            List<String> binBankStrList = IOUtils.readLines(reader);
            bankBinMappings = new HashMap();
            for (int i = binBankStrList.size() - 1; i >= 0; i--) {
                String[] item = binBankStrList.get(i).trim().split("====");
                bankBinMappings.put(item[1], item[0]);
            }
        } catch (Exception e) {
            LOGGER.error("load forbidden words failed", e);
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }
	
	/**
	 * 通过bin号获取银行名称
	 * @param binNo
	 * @return
	 */
	public static String getBankName(String binNo){
		String bankName=null;
		if(StringUtils.isNotEmpty(binNo)){
			bankName=bankBinMappings.get(binNo);
		}
		return bankName;
	}
	
	public static Map<String,String>  getBankMapping(){
		return bankBinMappings;
	}
}
